// WebSocketService.js
export default class WebSocketService {
	constructor(url) {
		this.url = url;
		this.socket = null;
		this.retryInterval = 5000; // 重试间隔 5 秒
		this.onMessageCallbacks = [];
		this.onErrorCallbacks = [];
		this.onCloseCallbacks = [];
		this.onOpenCallbacks = [];
		this.isManualClose = false; // 是否手动关闭标志
	}

	connect() {
		this.socket = new WebSocket(this.url);

		this.socket.onopen = () => {
			console.log('WebSocket连接已建立');
			this.isManualClose = false; // 重置手动关闭标志
			this.onOpenCallbacks.forEach(callback => callback(event.data));
		};

		this.socket.onmessage = (event) => {
			// console.log('收到消息:', event.data);
			this.onMessageCallbacks.forEach(callback => callback(event.data));
		};

		this.socket.onerror = (error) => {
			console.error('WebSocket错误:', error);
			this.onErrorCallbacks.forEach(callback => callback(error));
		};

		this.socket.onclose = () => {
			if (!this.isManualClose) {
				console.error('WebSocket连接已关闭，5秒后尝试重连...');
				this.onCloseCallbacks.forEach(callback => callback());
				setTimeout(() => this.connect(), this.retryInterval);
			} else {
				console.error('WebSocket连接已手动关闭');
			}
		};
	}

	send(message) {
		if (this.socket && this.socket.readyState === WebSocket.OPEN) {
			this.socket.send(message);
		} else {
			console.error('WebSocket未连接，无法发送消息');
		}
	}

	onMessage(callback) {
		this.onMessageCallbacks.push(callback);
	}

	onError(callback) {
		this.onErrorCallbacks.push(callback);
	}

	onClose(callback) {
		this.onCloseCallbacks.push(callback);
	}
	onOpen(callback) {
		this.onOpenCallbacks.push(callback);
	}

	close() {
		this.isManualClose = true; // 设置手动关闭标志
		if (this.socket) {
			this.socket.close();
		}
	}
}